/* eslint-disable @typescript-eslint/no-var-requires */
/*
 * @Author: Smthie Smthie@qq.com
 * @Date: 2024-05-13 10:06:44
 * @LastEditors: Smthie Smthie@qq.com
 * @LastEditTime: 2024-05-31 16:50:58
 * @FilePath: \ProtocolTool\src\preload\index.ts
 */
import { contextBridge } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
const os = require('os')
const { spawnSync } = require('child_process')
const iconv = require('iconv-lite')

const api = {
  // 最小化窗口
  minimize: () => electronAPI.ipcRenderer.send('minimize'),
  // 关闭窗口
  close: () => electronAPI.ipcRenderer.send('close'),
  // 新建窗口
  newWin: (path: string) => electronAPI.ipcRenderer.send('newWin', path),
  // 保存文件
  saveFile: (url, fileName) =>
    electronAPI.ipcRenderer.invoke('dialog:saveFile', '另存为', url, fileName),
  // 重启Java进程
  restartJava: (pid) => electronAPI.ipcRenderer.invoke('restartJava', pid)
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}

const getIP = () => {
  // 获取当前主机的网络接口信息
  const networkInterfaces = os.networkInterfaces()
  // console.log(networkInterfaces);
  const arrList = []

  // 遍历网络接口，找到主机的IP地址、子网掩码和默认网关
  Object.keys(networkInterfaces).forEach((interfaceName) => {
    const interfaces = networkInterfaces[interfaceName]
    interfaces.forEach((iface) => {
      // 找到IPv4地址
      if (iface.family === 'IPv4' && !iface.internal) {
        // console.log('interfaceName', interfaceName);
        // console.log('IP 地址:', iface.address);
        // console.log('子网掩码:', iface.netmask);
        // 默认网关通常是在同一子网内的第一个可用IP地址
        // const defaultGateway = iface.address.split('.').slice(0, 3).join('.') + '.1';
        // console.log('默认网关:', defaultGateway);
        const temp = {
          interfaceN: interfaceName,
          address: iface.address,
          netmask: iface.netmask,
          defaultGateway: iface.address.split('.').slice(0, 3).join('.') + '.1'
        }
        arrList.push(temp)

        const outputBuffer = spawnSync('netsh', ['interface', 'ip', 'show', 'config']).stdout
        const output = iconv.decode(outputBuffer, 'gbk') // 使用对应的编码，例如'gbk'是Windows的默认编码
        const lines = output.split('\r\n')
        // console.log(JSON.parse(JSON.stringify(lines)))

        const result = []
        let obj = {}

        for (let i = 0; i < lines.length; i++) {
          if (lines[i] === '') {
            if (Object.keys(obj).length !== 0) {
              result.push(obj)
              obj = {}
            }
          } else {
            const parts = lines[i]?.split(':')
            const key = parts[0]?.trim()
            const value = parts[1]?.trim()
            obj[key] = value
          }
        }

        console.log(result)
        // console.log(result[0]['DHCP 已启用'])
      }
    })
  })

  return arrList
}

contextBridge.exposeInMainWorld('getIpApi', {
  allInfo: getIP()
})

// const outputBuffer = spawnSync('netsh', ['interface', 'ip', 'show', 'config']).stdout;
// const output = iconv.decode(outputBuffer, 'gbk'); // 使用对应的编码，例如'gbk'是Windows的默认编码
// const lines = output.split('\r\n');
// // console.log(JSON.parse(JSON.stringify(lines)));

// // console.log(address);
// let arr = []
// for (let i = 0; i < lines.length; i++) {
//     if (lines[i].trim().startsWith('默认网关')) {
//         lines[i].split(':')[1].trim()
//         arr.push(lines[i].split(':')[1].trim())
//     }
// }

// const arrNum = [];
// const getDefaultGateway=(arr)=>{
//     let str1 =arr;
//     let str2 = address;
//     for (let k = 0; k < arr.length; k++) {
//         str1=arr[k]
//         calculateCommonLength(str1, str2)
//     }

//   return  findMaxIndex(arrNum)
// }

// function calculateCommonLength(str1, str2) {
//     const minLength = Math.min(str1.length, str2.length);
//     let commonLength = 0;

//     for (let i = 0; i < minLength; i++) {
//         if (str1[i] === str2[i]) {
//             commonLength++;
//         } else {
//             break;
//         }
//     }

//     return arrNum.push(commonLength);
// }

// function findMaxIndex(arr) {
//     let maxVal = Math.max(...arr);
//     let maxIndex = arr.indexOf(maxVal);
//     return maxIndex
// }

// //  console.log('默认网关',arr[getDefaultGateway(arr)])

//  defaultGateway = arr[getDefaultGateway(arr)]
